<?php

namespace Frieza\Modules\Ifttt\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmMsgSendDetails;
use Doraemon\model\AdmSysmsgType;
use Doraemon\model\Ifttt\IftttRuleGroup;
use Doraemon\model\Member;
use Biz\model\advertisement\MPositionBaseInfo;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\service\Ifttt as sIfttt;
use Doraemon\model\Ifttt\AdmIftttRule as mAdmIftttRule;
use Doraemon\tools\Log;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->addScript());
    }

    public function ruleList(Request $request, Content $content)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $search = [
            'page' => $page,
            'pageSize' => $pageSize,
        ];
        if (isset($params['dataType']) && $params['dataType']) {
            $search['dataType'] = $params['dataType'];
        }
        if (isset($params['ruleName']) && $params['ruleName']) {
            $search['ruleName'] = $params['ruleName'];
        }

        $list = sIfttt::getRuleListFromRemote($search);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function($filter){
                    $filter->disableIdFilter();
                    $filter->like('ruleName', '名称');
                    $filter->equal('dataType', '类型')->select(mAdmIftttRule::TYPE_DESC);
                });

                $grid->column("id", 'ID');
                $grid->column("ruleName", '名称')->width(300);
                $grid->column("dataType", '类型')->using(mAdmIftttRule::TYPE_DESC);
                $grid->column("triggerTime", '触发频率')->display(function () {
                    return round($this->triggerTime/24/3600, 5)." 天";
                });
                $grid->column("dataStatus", '状态')->editable('select', mAdmIftttRule::RULE_STATUS_DESC)->label([
                    mAdmIftttRule::RULE_STATUS_NORMAL => 'success',
                    mAdmIftttRule::RULE_STATUS_DELETED => 'danger'
                ]);
                $grid->column("createTime", '创建时间');
                $grid->column("updateTime", '更新时间');
                $grid->column("adminId", '操作人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->adminId)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    if ($actions->row->dataStatus == mAdmIftttRule::RULE_STATUS_DELETED) {
                        $actions->disableEdit();
                    }
                });
            });

        Admin::style('.multi-link-select{padding:5px 0;} .editable-click{color:#fff;border-bottom: none !important;} .editable-click:hover{color:#d8d2d2;}');

        $tab = new Tab();
        $tab->add('行为规则列表', $gridList->render(), true);
        $tab->addLink('添加行为规则', url('admin/Ifttt/create_rule'));
        $content->row($tab);
        return $content
            ->header('Ifttt管理')
            ->description('触发行为规则 (配置私信、下行消息、弹窗、推送等)')
            ->breadcrumb(['text' => '行为规则列表']);
    }

    public function createRule(Request $request, Content $content, $id = 0)
    {
        $row = [];
        if ($id) {
            $row = sIfttt::getRuleFromRemote($id);
            $header = "编辑行为规则";
        } else {
            $header = "添加行为规则";
        }
        $tab = new Tab();
        $form = new Form($row);

        if ($id) {
            $form->hidden('id');
        }
        $this->ruleForm($form, $id, $row);
        $form->action(url('admin/Ifttt/save_rule'));

        $tab->addLink('行为规则列表', url('admin/Ifttt/rule_list'));
        $tab->add($header, $form->render(), true);
        return $content
            ->header('Ifttt管理')
            ->description('触发行为规则 (配置私信、下行消息、弹窗、推送等)')
            ->breadcrumb(['text' => $header])
            ->row($tab);
    }

    public function ruleForm(Form $form, $id = 0, $row = [])
    {
        $form->text('rule_name', '名称');
        $form->decimal("trigger_time", '触发频率')->default(1)->help('多久触发一次，单位：天');
        $form->text('extend', '扩展项')->help("选填，当任务需要定制化时使用");
        $form->fieldChange('data_type', '类型', $form)
            ->options(mAdmIftttRule::TYPE_DESC)
            ->default(mAdmIftttRule::TYPE_SYS_MSG)
            ->callablePreCommon(function (Form $form){
            })->callableMap([
                mAdmIftttRule::TYPE_SYS_MSG => function (Form $form) {
                    $form->html("<div style='height:3px;'></div>");
                    $form->fieldChange('sys_msg.type', '通知类型', $form)
                        ->options([1 => '系统消息', 2 => '通知'])
                        ->default(2)
                        ->callablePreCommon(function (Form $form){
                        })->callableMap([
                            1 => function (Form $form) {
                                $form->select('sys_msg.sub_type', '通知子类型')
                                    ->options(AdmSysmsgType::getSysmsgType(AdmSysmsgType::TYPE_MSG));
                            },
                            2 => function (Form $form) {
                                $form->select('sys_msg.sub_type', '通知子类型')
                                    ->options(AdmSysmsgType::getSysmsgType(AdmSysmsgType::TYPE_NOTICE));
                            }
                        ]);
                    $form->text('sys_msg.title', '发送标题');
                    $form->textarea('sys_msg.content', '发送内容')->style("min-height","100px");
                    $form->imgUpload('sys_msg.pic_id','上传图片');
                    $form->multiLinkSelect('sys_msg.link', '跳转链接');
                    $form->html("<div style='height:3px;'></div>");
                },
                mAdmIftttRule::TYPE_IM_SEND => function (Form $form) {
                    $user_list = Member::getUsers(User::getOfficeUidFromServerConf() ?: User::OFFICE_UID);
                    $from_users = [];
                    foreach ($user_list as $user) {
                        $from_users[$user['uid']] = $user['nick'];
                    }
                    $form->html("<div style='height:3px;'></div>");
                    $form->select('im.send_user', '发送人')->options($from_users);
                    $form->radio('im.con_type', '发送类型')
                        ->options([AdmMsgSendDetails::CON_TYPE_TEXT => '文本', AdmMsgSendDetails::CON_TYPE_IMAGE => '图片', AdmMsgSendDetails::CON_TYPE_IMG_TXT => '图文'])
                        ->default(0)
                        ->when(AdmMsgSendDetails::CON_TYPE_TEXT, function (Form $form) {
                            $form->textarea("im.content", '发送内容');
                        })->when(AdmMsgSendDetails::CON_TYPE_IMAGE, function (Form $form) {
                            $form->imgUpload("im.pic_id", '上传图片')->help('单图，必须需要上传');
                        })->when(AdmMsgSendDetails::CON_TYPE_IMG_TXT, function (Form $form) {
                            $form->text("im.title", '标题');
                            $form->textarea("im.desc", '描述');
                            $form->imgUpload("im.cover_img", '图片')->help('单图，必须需要上传');
                            $form->multiLinkSelect("im.link", '链接');
                        })->when(AdmMsgSendDetails::CON_TYPE_CARD, function (Form $form) {
                            $form->text("im.title", '标题');
                            $form->text("im.desc", '描述');
                            $form->multiLinkSelect("im.link", '卡片链接');
                            $form->imgUpload("im.cover_img", '图片')->help('单图，必须需要上传');
                            $form->text("im.button_text", '按钮文字');
                            $form->multiLinkSelect("im.button_link", '按钮链接');
                        });
                    $form->html("<div style='height:3px;'></div>");
                },
                mAdmIftttRule::TYPE_MSG_PUSH => function (Form $form) {
                    $form->html("<div style='height:3px;'></div>");
                    $form->text('push.title', '推送标题');
                    $form->textarea('push.content', '推送内容');
                    $form->multiLinkSelect('push.link', '跳转链接')->help("推送的链接必须选择");
                },
                mAdmIftttRule::TYPE_CLIENT_POPUP => function (Form $form) use ($id, $row) {
                    $form->html("<div style='height:1px;'></div>");
                    //$form->radio('popup.intent.action', '返回时弹出')->options([0=>'否',1=>'是'])->default(0);
                    $form->radio('popup.reason', '投放原因')->options(MPositionBaseInfo::REASON_MAP)->default(MPositionBaseInfo::REASON_TYPE_OPERATE);
                    //$form->select('popup.intent.level', '弹窗等级')->options(array_slice(range(0,10), 1, 10, true));
                    $form->select('popup.intent.pageName', '弹出位置')->options(sIfttt::POPUP_PAGE_NAME);
                    $form->radio('popup.type', '弹窗配置')
                        ->options([1 => '样式1', 2 => '样式2', 3 => '样式3', 7 => '样式7', 8 => '样式8', 10 => '样式10'])
                        ->help("<a href='https://confluence.haohaozhu.me/pages/viewpage.action?pageId=32014453' target='_blank'>弹窗样式参考</a>")
                        ->default(1)
                        ->when(1, function (Form $form) {
                            $form->text("popup.popup_info.1.title", '标题');
                            $form->number("popup.popup_info.1.title_size", '标题字号')->default(16);
                            $form->color("popup.popup_info.1.title_color", '标题颜色')->default('#333')->hex();
                            $form->text("popup.popup_info.1.desc", '描述');
                            $form->number("popup.popup_info.1.desc_size", '描述字号')->default(16);
                            $form->color("popup.popup_info.1.desc_color", '描述颜色')->default('#666')->hex();
                            $form->imgUpload('popup.popup_info.1.img_url', '背景图')->help('背景图，必须需要上传');
                            $form->color("popup.popup_info.1.button_list.0.background_color", '按钮背景色[1]')->default('#333')->hex();
                            $form->multiLinkSelect('popup.popup_info.1.button_list.0.link', '按钮链接[1]');
                            $form->text("popup.popup_info.1.button_list.0.title", '按钮文字[1]');
                            $form->color("popup.popup_info.1.button_list.0.color", '按钮颜色[1]')->default('#333')->hex();
                            $form->text("popup.popup_info.1.button_list.0.scenes_type", '场景标识[1]');
                            $form->color("popup.popup_info.1.button_list.1.background_color", '按钮背景色[2]')->default('#333')->hex();
                            $form->multiLinkSelect('popup.popup_info.1.button_list.1.link', '按钮链接[2]');
                            $form->text("popup.popup_info.1.button_list.1.title", '按钮文字[2]');
                            $form->color("popup.popup_info.1.button_list.1.color", '按钮颜色[2]')->default('#333')->hex();
                            $form->text("popup.popup_info.1.button_list.1.scenes_type", '场景标识[2]');
                        })->when(2, function (Form $form) {
                            $form->text("popup.popup_info.2.title", '标题');
                            $form->text("popup.popup_info.2.desc", '描述');
                            $form->multiLinkSelect('popup.popup_info.2.button_list.0.link', '按钮链接[1]');
                            $form->text("popup.popup_info.2.button_list.0.title", '按钮文字[1]');
                            $form->text("popup.popup_info.2.button_list.0.scenes_type", '场景标识[1]');
                            $form->multiLinkSelect('popup.popup_info.2.button_list.1.link', '按钮链接[2]');
                            $form->text("popup.popup_info.2.button_list.1.title", '按钮文字[2]');
                            $form->text("popup.popup_info.2.button_list.1.scenes_type", '场景标识[2]');
                        })->when(3, function (Form $form) {
                            $form->imgUpload('popup.popup_info.3.img_url', '背景图')->help('背景图，必须需要上传');
                            $form->multiLinkSelect('popup.popup_info.3.link', '跳转链接');
                        })->when(7, function (Form $form) {
                            $form->text("popup.popup_info.7.title", '标题');
                            $form->number("popup.popup_info.7.title_size", '标题字号')->default(16);
                            $form->color("popup.popup_info.7.title_color", '标题颜色')->default('#333')->hex();
                            $form->text("popup.popup_info.7.desc", '描述');
                            $form->number("popup.popup_info.7.desc_size", '描述字号')->default(16);
                            $form->color("popup.popup_info.7.desc_color", '描述颜色')->default('#666')->hex();
                            $form->imgUpload('popup.popup_info.7.img_url', '背景图')->help('背景图，必须需要上传');
                            $form->color("popup.popup_info.7.button_list.0.background_color", '按钮背景色[1]')->default('#333')->hex();
                            $form->multiLinkSelect('popup.popup_info.7.button_list.0.link', '按钮链接[1]');
                            $form->text("popup.popup_info.7.button_list.0.title", '按钮文字[1]');
                            $form->color("popup.popup_info.7.button_list.0.color", '按钮颜色[1]')->default('#333')->hex();
                            $form->text("popup.popup_info.7.button_list.0.scenes_type", '场景标识[1]');
                            $form->color("popup.popup_info.7.button_list.1.background_color", '按钮背景色[2]')->default('#333')->hex();
                            $form->multiLinkSelect('popup.popup_info.7.button_list.1.link', '按钮链接[2]');
                            $form->text("popup.popup_info.7.button_list.1.title", '按钮文字[2]');
                            $form->color("popup.popup_info.7.button_list.1.color", '按钮颜色[2]')->default('#333')->hex();
                            $form->text("popup.popup_info.7.button_list.1.scenes_type", '场景标识[2]');
                        })->when(8, function (Form $form) {
                            $form->text("popup.popup_info.8.title", '标题');
                            $form->number("popup.popup_info.8.title_size", '标题字号')->default(16);
                            $form->color("popup.popup_info.8.title_color", '标题颜色')->default('#333')->hex();
                            $form->text("popup.popup_info.8.desc", '描述');
                            $form->number("popup.popup_info.8.desc_size", '描述字号')->default(16);
                            $form->color("popup.popup_info.8.desc_color", '描述颜色')->default('#666')->hex();
                            $form->imgUpload('popup.popup_info.8.img_url', '头像');
                            $form->radio("popup.popup_info.8.img_type", '图片格式')->options([1=>'圆形',2=>'方形'])->default(1);
                            $form->color("popup.popup_info.8.bg_color", '背景颜色')->default('#333')->hex();
                            $form->decimal("popup.popup_info.8.bg_transparent", '背景透明度')->default(1)->help("示例：0.5, 取值在0~1之间");
                            $form->radio("popup.popup_info.8.show_type", '展示位置')->options([0=>'底部',1=>'顶部'])->default(0);
                            $form->number("popup.popup_info.8.disappear", '消失时间')->min(1)->default(3);
                            $form->radio("popup.popup_info.8.show_close", '是否展示关闭按钮')->options([1=>'展示',0=>'不展示'])->default(1);
                            $form->color("popup.popup_info.8.button_list.0.background_color", '按钮背景色[1]')->default('#333')->hex();
                            $form->multiLinkSelect('popup.popup_info.8.button_list.0.link', '按钮链接[1]');
                            $form->text("popup.popup_info.8.button_list.0.title", '按钮文字[1]');
                            $form->color("popup.popup_info.8.button_list.0.color", '按钮颜色[1]')->default('#333')->hex();
                            $form->text("popup.popup_info.8.button_list.0.scenes_type", '场景标识[1]');
                            $form->imgUpload('popup.popup_info.8.button_list.0.icon_url', '小图标');
                        })->when(9, function (Form $form) {
//                            $form->fieldset("背景配置", function (Form $form) {
//                                $form->radio("popup.popup_info.9.close", '关闭按钮位置')->options([0 => '无', 1 => '底部', 2 => "右"])->default(0);
//                                $form->imgUpload("popup.popup_info.9.backgroundArea.pic_url", '背景图');
//                                $form->multiLinkSelect("popup.popup_info.9.backgroundArea.link", '背景图链接');
//                            });
//                            $form->fieldset("图片区配置", function (Form $form) {
//                                $form->radio("popup.popup_info.9.picArea.position", "图片位置")->options([0 => '中', 1 => '下', 2 => "上"]);
//                                $form->imgUpload("popup.popup_info.9.picArea.pic_url", '主图');
//                                $form->multiLinkSelect("popup.popup_info.9.picArea.link", '主图链接');
//                                $form->text("popup.popup_info.9.picArea.height", '图片区域高度');
//                                $form->text("popup.popup_info.9.picArea.img_w", '图片宽')->help('宽度不少于315');
//                                $form->text("popup.popup_info.9.picArea.img_h", '图片高');
//                                $form->ckEditor("popup[popup_info][9][textArea][text]", "文字区内容")
//                                    ->setSimpleToolBar()
//                                    ->setValueColumn("popup.popup_info.9.textArea.text")
//                                    ->setHeight(200);
//                            });
//                            $form->fieldset("按钮配置(最多支持两个)", function (Form $form) {
//                                $form->color("popup.popup_info.9.button_list.0.background_color", '按钮背景色[1]')->default('#333');
//                                $form->multiLinkSelect('popup.popup_info.9.button_list.0.link', '按钮链接[1]');
//                                $form->text("popup.popup_info.9.button_list.0.title", '按钮文字[1]');
//                                $form->color("popup.popup_info.9.button_list.0.color", '按钮颜色[1]')->default('#333');
//                                $form->text("popup.popup_info.9.button_list.0.scenes_type", '场景标识[1]');
//                                $form->divider();
//                                $form->color("popup.popup_info.9.button_list.1.background_color", '按钮背景色[2]')->default('#333');
//                                $form->multiLinkSelect('popup.popup_info.9.button_list.1.link', '按钮链接[2]');
//                                $form->text("popup.popup_info.9.button_list.1.title", '按钮文字[2]');
//                                $form->color("popup.popup_info.9.button_list.1.color", '按钮颜色[2]')->default('#333');
//                                $form->text("popup.popup_info.9.button_list.1.scenes_type", '场景标识[2]');
//                            });
                        })->when(10, function (Form $form) use ($id, $row) {
                            $form->radio("popup.popup_info.10.show_close", '是否展示关闭按钮')->options([1=>'展示',0=>'不展示'])->default(1);
                            $form->text("popup.popup_info.10.title", '标题');
                            $form->text("popup.popup_info.10.desc", '副标题');
                            $form->html($this->htmlTpl1())->plain();
                            $index = 0;
                            if ($id && isset($row['popup']['popup_info'][10]['button_list'])) {
                                for ($i=$index;$i<count($row['popup']['popup_info'][10]['button_list']);$i++) {
                                    $form->html($this->htmlTpl5($i))->plain();
                                    $form->text("popup.popup_info.10.button_list.{$i}.title", '按钮文字');
                                    $form->multiLinkSelect("popup.popup_info.10.button_list.{$i}.link", '按钮链接');
                                    $form->html("<input type='hidden' name='popup[popup_info][10][button_list][{$i}][is_remove]' class='ipt-remove' value='0' />")->plain();
                                    $form->html($this->htmlTpl3())->plain();
                                }
                                $index = count($row['popup']['popup_info'][10]['button_list']);
                            }
                            for ($i=$index;$i<10;$i++) {
                                $form->html($this->htmlTpl2($i))->plain();
                                $form->text("popup.popup_info.10.button_list.{$i}.title", '按钮文字');
                                $form->multiLinkSelect("popup.popup_info.10.button_list.{$i}.link", '按钮链接');
                                $form->html("<input type='hidden' name='popup[popup_info][10][button_list][{$i}][is_remove]' class='ipt-remove' value='1' />")->plain();
                                $form->html($this->htmlTpl3())->plain();
                            }
                            $form->html($this->htmlTpl4())->plain();
                        });
                    $form->html("<div style='height:1px;'></div>");
                },
                mAdmIftttRule::TYPE_SURVEY => function (Form $form) use ($id, $row) {
                    $form->html("<div style='height:3px;'></div>");
                    $form->decimal("survey.show_time", '展示时间')->default(1)->help('展示多长时间，单位：小时');
                    $form->select('survey.location_type', "展示位置")
                        ->options(mAdmIftttRule::SHOW_LOCATION_DESC)
                        ->when('=', mAdmIftttRule::LOCATION_TYPE_RECOMMEND_LINE, function ($form) {
                            $form->number("survey.show_location.page", "第几页")->default(0)->min(0);
                            $form->number("survey.show_location.place", "第几位")->default(0)->min(0);
                        });
                    $form->radio("survey.survey_type", '卡片配置', $form)
                        ->options(mAdmIftttRule::SURVEY_TYPE_DESC)
                        ->default(mAdmIftttRule::SURVEY_TYPE_IMAGE)
                        ->when(mAdmIftttRule::SURVEY_TYPE_IMAGE, function (Form $form) {
                            $form->imgUpload("survey.pic_id", '背景图');
                            $form->multiLinkSelect('survey.link', '跳转链接')->help("跳转链接必须选择");
                        })->when(mAdmIftttRule::SURVEY_TYPE_RICH_TEXT, function (Form $form) use ($id, $row) {
                            $form->text("survey.desc", "引导文案");
                            $form->text("survey.question", "问题")->placeholder("请输入您的问题，限制20个字")->help("每个问题最多只展示4个选项，选项≥4个的，仅展示前4个选项")->attribute('maxlength',20);
                            $form->text("survey.option.0.value", '选项')->placeholder("请输入您的选项，限制10个字")->attribute('maxlength',10);
                            $form->html('<div id="has-many-survey_option" class="has-many-survey_option" style="padding-bottom: 30px;"><div class="has-many-survey_option-forms">')->plain();
                            $index = 1;
                            if ($id && $row['survey']['option']) {
                                for ($i=$index;$i<count($row['survey']['option']);$i++) {
                                    $form->html('<div class="has-many-survey_option-form fields-group" data-id="'.$i.'">')->plain();
                                    $form->text("survey.option.{$i}.value", '选项')->placeholder("请输入您的选项，限制10个字")->attribute('maxlength',10);
                                    $form->html("<input type='hidden' name='survey[option][{$i}][is_remove]' class='survey-remove fom-removed' value='0' />")->plain();
                                    $form->html($this->htmlTpl3())->plain();
                                }
                                $index = count($row['survey']['option']);
                            }
                            for ($i=$index;$i<4;$i++) {
                                $form->html('<div class="has-many-survey_option-form fields-group" data-id="'.$i.'" style="display: none;">')->plain();
                                $form->text("survey.option.{$i}.value", '选项')->placeholder("请输入您的选项，限制10个字")->attribute('maxlength',10);
                                $form->html("<input type='hidden' name='survey[option][{$i}][is_remove]' class='survey-remove fom-removed' value='1' />")->plain();
                                $form->html($this->htmlTpl3())->plain();
                            }
                            $form->html($this->htmlTpl4())->plain();
                        })->when(mAdmIftttRule::SURVEY_TYPE_CARD_TOPIC, function (Form $form) {
                            $form->imgUpload('survey.topic.photo', '背景图');
                            $form->imgUpload('survey.topic.module_icon', '模块图标');
                            $form->text('survey.topic.sub_title', '标题');
                            $form->radio('survey.topic.guide', '引导模块')->options([0 => '隐藏', 1 => '展示']);
                            $form->multiLinkSelect('survey.topic.link', '跳转链接');
                        })->when(mAdmIftttRule::SURVEY_TYPE_CARD_SIMILAR, function (Form $form) {
                            $form->imgUpload('survey.similar.photo', '封面图');
                            $form->imgUpload('survey.similar.module_icon', '模块图标');
                            $form->text('survey.similar.title', '主标题');
                            $form->text('survey.similar.sub_title', '副标题');
                            $form->imgUpload('survey.similar.background_image', '文字区背景图');
                            $form->text('survey.similar.uid', '发布者uid');
                            $form->multiLinkSelect('survey.similar.link', '跳转链接');
                        });
                }
            ]);
    }

    public function saveRule(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            if (empty($params['rule_name'])) {
                throw new \Exception('请输入名称');
            }
            if (isset($params['im']['content'])) {
                $textLen = mb_strlen($params['im']['content']);
                if ($textLen > 200) {
                    throw new \Exception('私信发送文本不能超过200个字符，当前已输入'.$textLen.'个字符');
                }
            }
            if (isset($params['popup']['reason'])) {
                if (in_array($params['popup']['reason'], [
                    MPositionBaseInfo::REASON_TYPE_SUPER,
                    MPositionBaseInfo::REASON_TYPE_BUSINESS,
                    MPositionBaseInfo::REASON_TYPE_KA,
                    MPositionBaseInfo::REASON_TYPE_PRODUCT,
                ])) {
                    $params['popup']['intent']['level'] = 10;
                } else {
                    $params['popup']['intent']['level'] = 1;
                }
            }
            if (isset($params['popup']['popup_info']['button_list'])) {
                $button_list = [];
                foreach ($params['popup']['popup_info']['button_list'] as $item) {
                    if (isset($item['is_remove'])) {
                        if ($item['is_remove'] == 0) {
                            unset($item['is_remove']);
                            $button_list[] = $item;
                        }
                    } elseif ($item['title']) {
                        $button_list[] = $item;
                    }
                }
                $params['popup']['popup_info']['button_list'] = $button_list;
            }
            if (isset($params['survey']['option'])) {
                $survey_option = [];
                foreach ($params['survey']['option'] as $item) {
                    if (isset($item['_remove_']) && $item['_remove_'] == 1) {
                        continue;
                    }
                    if (trim($item['value'])) {
                        $survey_option[] = trim($item['value']);
                    }
                }
                $params['survey']['option'] = $survey_option;
            }
            if (isset($params['survey']['survey_type']) && $params['survey']['survey_type'] == mAdmIftttRule::SURVEY_TYPE_RICH_TEXT) {
                if (empty($params['survey']['question']) || count($params['survey']['option']) < 2) {
                    throw new \Exception("您有信息尚未填写");
                }
            }

            $result = sIfttt::saveTaskRuleToRemote($params);
            if ($result) {
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect(url('/admin/Ifttt/rule_list'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function updateRuleStatus(Request $request, $id = 0)
    {
        $params = $request->input();

        $result = sIfttt::alterRuleStatusToRemote($id, intval($params['value']));
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "操作成功"
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败"
            ]);
        }
    }

    public function ruleGroupList(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $list = IftttRuleGroup::getListByPage($page, $pageSize);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableActions();

                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                    $create->text('trigger_tag', '触发标识');
                    $create->text('rule_ids', '规则ID');
                });

                $grid->column("id", 'ID');
                $grid->column("trigger_tag", '触发标识')->width(200)->editable();
                $grid->column("rule_ids", '规则ID')->editable();
                $grid->column("add_time", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                });
                $grid->column("edit_time", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edit_time);
                });
            });

        $tab = new Tab();
        $tab->add('分组列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('Ifttt规则管理')
            ->description('规则分组管理')
            ->breadcrumb(['text' => '规则分组列表']);
    }

    public function ruleGroupSubmit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            if ($id) {
                $result = IftttRuleGroup::updateInfo([$params['name']=>$params['value']], ['id'=>$id]);
            } else {
                $result = IftttRuleGroup::addInfo(['trigger_tag'=>$params['trigger_tag'], 'rule_ids'=>trim($params['rule_ids'])]);
            }

            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    private function addScript()
    {
        return <<<SCRIPT
//        $(document).ready(function(){
//           for(var i in CKEDITOR.instances) {
//               var ck=CKEDITOR.instances[i]; 
//               ck.on( 'instanceReady', function( ev ) {
//               var editor = ev.editor;
//               editor.setReadOnly( false );
//           });
//        }});
        $("body").on('click', '.editable-submit', function(){
            $(".grid-editable-data_status").bind("DOMNodeInserted", function(e){
                var oText = $(e.target).html();
                $(e.target).parent().removeAttr('class');
                var oClassName = 'label';
                if (oText == '测试') {
                    oClassName = "label label-warning";
                } else if (oText == '上线') {
                    oClassName = "label label-success";
                } else if (oText == '下线') {
                    oClassName = "label label-danger";
                } else if (oText == '正常') {
                    oClassName = "label label-success";
                } else if (oText == '删除') {
                    oClassName = "label label-danger";
                }
                $(e.target).parent().addClass(oClassName);
            });
        });
        $('#has-many-con').off('click', '.add').on('click', '.add', function () {
            $('.has-many-con-form').eq($('.has-many-con-form:visible').length).find(".ipt-remove").val(0);
            $('.has-many-con-form').eq($('.has-many-con-form:visible').length).show();
            if ($('.has-many-con-form').length == $('.has-many-con-form:visible').length) {
                $(".add-btn").hide();
            }
            return false;
        });
        $('#has-many-con').off('click', '.remove').on('click', '.remove', function () {
            $(this).closest('.has-many-con-form').find(".ipt-remove").val(1);
            $(this).closest('.has-many-con-form').hide();
            var index = $(this).closest('.has-many-con-form').attr("data-id");
            $("textarea[name='content["+index+"]'").val("");
            $(this).closest('.has-many-con-form').appendTo($(".has-many-con-forms"));
            if ($('.has-many-con-form').length > $('.has-many-con-form:visible').length) {
                $(".add-btn").show();
            }
            return false;
        });
        $('#has-many-survey_option').off('click', '.add').on('click', '.add', function () {
            $('.has-many-survey_option-form').eq($('.has-many-survey_option-form:visible').length).find(".survey-remove").val(0);
            $('.has-many-survey_option-form').eq($('.has-many-survey_option-form:visible').length).show();
            if ($('.has-many-survey_option-form').length == $('.has-many-survey_option-form:visible').length) {
                $("#has-many-survey_option .add-btn").hide();
            }
            return false;
        });
        $('#has-many-survey_option').off('click', '.remove').on('click', '.remove', function () {
            $(this).closest('.has-many-survey_option-form').find(".survey-remove").val(1);
            $(this).closest('.has-many-survey_option-form').hide();
            var index = $(this).closest('.has-many-survey_option-form').attr("data-id");
            $("#survey_option_"+index+"_value").val("");
            $(this).closest('.has-many-survey_option-form').appendTo($(".has-many-survey_option-forms"));
            if ($('.has-many-survey_option-form').length > $('.has-many-survey_option-form:visible').length) {
                $("#has-many-survey_option .add-btn").show();
            }
            return false;
        });
SCRIPT;
    }


    private function htmlTpl1()
    {
        return <<<HTML
        <div class="row">
            <div class="col-sm-2"><h4 class="pull-right">配置按钮</h4></div>
            <div class="col-sm-8"></div>
        </div>
        <hr style="margin-top: 0px;">
        <div id="has-many-con" class="has-many-con">
            <div class="has-many-con-forms"> 
HTML;
    }
    private function htmlTpl2($i)
    {
        return <<<HTML
        <div class="has-many-con-form fields-group" data-id="$i" style="display: none;">
HTML;
    }
    private function htmlTpl3()
    {
        return <<<HTML
            <div class="form-group">
                <label class="col-sm-2 control-label"></label>
                <div class="col-sm-8">
                    <div class="remove btn btn-warning btn-sm pull-right"><i class="fa fa-trash"></i>&nbsp;移除</div>
                </div>
            </div>
            <hr>
        </div>
HTML;
    }
    private function htmlTpl4()
    {
        return <<<HTML
        </div>
        <div class="form-group add-btn">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-8">
                <div class="add btn btn-success btn-sm"><i class="fa fa-save"></i>&nbsp;新增</div>
            </div>
        </div>
    </div>
HTML;
    }
    private function htmlTpl5($i)
    {
        return <<<HTML
        <div class="has-many-con-form fields-group" data-id="$i">
HTML;
    }

}
